package com.hisense.ovcloud.asop.clients;

import com.hisense.ovcloud.asop.dto.clients.CustomerDto;
import com.hisense.ovcloud.asop.dto.req.CheckTokenReq;
import com.hisense.ovcloud.asop.dto.resp.CheckTokenResp;
import com.hisense.ovcloud.asop.dto.resp.QueryCustomerIdResp;
import com.hisense.ovcloud.asop.tools.HeaderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
@Slf4j
public class BasicDataClient {

    @Value("${basicDataBaseAddr:http://basic-data:9198}")
    private String basicDataBaseAddr;

    private final WebClient webClient;

    public BasicDataClient(@Qualifier("base") WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<List<CustomerDto>> queryCustomerInfo(String email){
        return webClient.get()
                .uri(basicDataBaseAddr + "/v2/appUser/msg/getCustomerIdAndUserId?userId=" + email)
                .header("rearDoor", "1")
                .retrieve()
                .bodyToMono(QueryCustomerIdResp.class)

                .flatMap(r -> Mono.just(r.getData()));
    }

    public Mono<CheckTokenResp> verifyToken(ServerRequest req){
        String token = HeaderUtil.getHeader(req, "Token");
        System.out.println("token: " + token);
        if(StringUtils.isNotEmpty(token)){
            return webClient.post()
                    .uri(basicDataBaseAddr + "/user/checkToken")
                    .bodyValue(CheckTokenReq.builder().token(token).build())
                    .retrieve()
                    .bodyToMono(CheckTokenResp.class)
                    .doOnSuccess(x -> System.out.println("x: "+ x));
        }else{
            return Mono.just(CheckTokenResp.builder().build());
        }
    }
}
